package com.recharge.common.util;

public class Des3Encryption {
    public static final String CHAR_ENCODING = "UTF-8";

    public static String encryptToHex(String key, String data) {
        try {
            byte[] keyByte = key.getBytes(CHAR_ENCODING);
            byte[] dataByte = data.getBytes(CHAR_ENCODING);
            byte[] valueByte = MessageAuthenticationCode.des3Encryption(keyTo24Byte(keyByte), dataByte);
            //将结果转换成为16进制
            String value = toHex(valueByte);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] decode(byte[] key, byte[] value) throws Exception {
        return MessageAuthenticationCode.des3Decryption(keyTo24Byte(key), value);
    }

    private static byte[] keyTo24Byte(byte[] keyByte) {
        if (keyByte == null || keyByte.length == 0) {
            throw new RuntimeException("keyByte is null");
        }
        byte[] toByte = null;
        if (keyByte.length == 24) {
            return keyByte;
        } else if (keyByte.length > 24) {
            toByte = new byte[24];
            System.arraycopy(keyByte, 0, toByte, 0, 24);
        } else {
            toByte = new byte[24];
            System.arraycopy(keyByte, 0, toByte, 0, keyByte.length);
        }
        return toByte;
    }

    private static String toHex(byte input[]) {
        if (input == null)
            return null;
        StringBuffer output = new StringBuffer(input.length * 2);
        for (int i = 0; i < input.length; i++) {
            int current = input[i] & 0xff;
            if (current < 16)
                output.append("0");
            output.append(Integer.toString(current, 16));
        }

        return output.toString();
    }

    public static void main(String[] args) throws Exception {
        String key = "test12345678901234";
        String value = "1234567890123456789";
        String encrypt = encryptToHex(key, value);
        System.out.println("encrypt: " + encrypt);
        System.out.println("decrypt:" + new String(decode(key.getBytes(), fromHex(encrypt)), "UTF-8"));
    }

    public static byte[] fromHex(String input) {
        if (input == null) {
            return null;
        } else {
            byte[] output = new byte[input.length() / 2];

            for (int i = 0; i < output.length; ++i) {
                output[i] = (byte) Integer.parseInt(input.substring(i * 2, (i + 1) * 2), 16);
            }

            return output;
        }
    }
}